package com.aitesting.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.aitesting.common.CommonPage;
import com.aitesting.dto.UserDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.aitesting.common.CommonResult;
import com.aitesting.model.User;
import com.aitesting.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * @author zz
 * @since 2022-02-20
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据id查询用户信息
     * @param id 用户id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public CommonResult<User> getById(@PathVariable("id") Integer id) {
        return CommonResult.success(userService.getById(id));
    }

    /**
     * 根据用户名查询用户信息(支持模糊查询)
     * @param username 用户名
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/simpleList", method = RequestMethod.GET)
    public CommonResult<List<User>> simpleList(@RequestParam(value = "username") String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        /*queryWrapper.eq("username", username);  //精确查询*/
        queryWrapper.like("username", username);    //模糊查询
        return CommonResult.success(userService.list(queryWrapper));
    }

    /**
     * 查询所有用户信息
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public CommonResult<User> getList() {
        return CommonResult.success(userService.list());
    }

    /**
     * 新增用户
     * @param user 用户对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public CommonResult<User> create(@Validated @RequestBody User user, BindingResult result){
        //如何验证user数据的合法性，基于切面编程实现
        //密码如何加密?
        boolean isOk = userService.save(user);
        if (isOk) {
            log.debug("创建用户成功 {}", user);
            return CommonResult.success(user);
        }else {
            log.error("新增用户失败,用户数据不合法 {}", user);
            return CommonResult.failed();
        }
    }

    /**
     * 根据id删除用户
     * @param id 用户id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public CommonResult<User> delete(@PathVariable Integer id) {
        boolean isOk = userService.removeById(id);
            if (isOk) {
                return CommonResult.success(null);
            }else {
                return CommonResult.failed();
            }
    }

    /**
     * 根据id更新用户信息
     * @param user 用户对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public CommonResult<User> update(@RequestBody User user) {
        //如何验证user数据的合法性，基于切面编程实现？
        //密码如何加密？
        boolean isOk = userService.updateById(user);
        if (isOk) {
            log.debug("更新用户成功 {}", user);
            return CommonResult.success(user);
        }else {
            log.error("更新用户失败,用户数据不合法 {}", user);
            return CommonResult.failed();
        }
    }

    /**
     * 分页查询用户信息
     * @param pageIndex 第几页
     * @param pageSize 每页大小
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<User> listPage(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        Page<User> page = new Page<>(pageIndex, pageSize);
        Page<User> userPage = userService.page(page);
        return CommonResult.success(CommonPage.restPage(userPage));
    }

    /**
     * 登录
     * @param userDto username,password
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult<User> login(@RequestBody UserDto userDto){
        SaTokenInfo saTokenInfo = userService.login(userDto.getUsername(), userDto.getPassword());
        if (saTokenInfo == null) {
            log.debug("login failed:{}", userDto.getUsername());
            return CommonResult.failed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", saTokenInfo.getTokenValue());
        tokenMap.put("tokenHead", saTokenInfo.getTokenName());
        return CommonResult.success(tokenMap);
    }

    /**
     * 登出
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        StpUtil.logout();
        return CommonResult.success(null);
    }
}

